<?php
use Swoole\Runtime;
use Swoole\Coroutine;
use Swoole\Coroutine\MySQL;
use function Swoole\Coroutine\run;
Runtime::enableCoroutine(true, SWOOLE_HOOK_ALL | SWOOLE_HOOK_CURL);

$start_time = microtime(true);

require  'global_default_function.php';

function getSiteList($header, $database, $user) {
	$doResponse = HttpPost('https://api.baidu.com/json/tongji/v1/ReportService/getData', $header);
	if( !$doResponse ) {
		return;
	}
	$bodyArray = json_decode($doResponse, true);
	if( !is_array($bodyArray) ) {
		return;
	}
	if( !isset($bodyArray['header']) ) {
		return;
	}
	if( !isset($bodyArray['header']['desc']) ) {
		return;
	}
	//[0] => 2022/08/15 22:37:46
	//[1] => 江西上饶望仙谷风景区
	//[2] => http://jx2022a.zyjqgj.com/?bd_vid=1980458675518695796&hdfshare=19979169220
	if( $bodyArray['header']['desc'] == 'success' ) {
		if( isset($bodyArray['body']['data'][0]['result']['items'][1]) ) {
			if( is_array($bodyArray['body']['data'][0]['result']['items'][1]) ) {
				$database->query( " UPDATE cfg_expand SET `countStat` = 0, `countRquota` = '{$bodyArray['header']['rquota']}', `countMessage` = '', `lastDatetime` = NOW() WHERE username = '{$user['username']}' ");
				foreach ($bodyArray['body']['data'][0]['result']['items'][1] as $value) {
					if(stripos($value[2], "bd_vid=") !== false) {
					    $value[2] = urldecode($value[2]);
						$endTime   = date("Y-m-d H:i:s"); // 访问时间
						$startTime = date("Y-m-d H:i:s", strtotime ("-60 minute", strtotime($value[0]))); // 访问时间
						$value[1]  = str_replace(["\\", "'", ','], '', $value[1]); // 搜索词
						$queryAccess = $database->query("SELECT `id` FROM cfg_access where `companyId` = {$user['companyId']} AND `userid` = '{$user['userid']}' AND `userType` = 1 AND `accessTime` BETWEEN '{$startTime}' AND '{$endTime}' AND `url` = '{$value[2]}' AND `word` is NULL");
						if( isset($queryAccess[0]['id']) ) {
							$database->query( " UPDATE cfg_access SET `word` = '{$value[1]}' WHERE id = '{$queryAccess[0]['id']}'; ");
						}
						$queryCopy = $database->query("SELECT `id` FROM cfg_copy where `companyId` = {$user['companyId']} AND `userid` = '{$user['userid']}' AND `userType` = 1 AND `copyTime` BETWEEN '{$startTime}' AND '{$endTime}' AND `url` = '{$value[2]}' AND `word` is NULL");
						if( isset($queryCopy[0]['id']) ) {
							$database->query( " UPDATE cfg_copy SET `word` = '{$value[1]}' WHERE id = '{$queryCopy[0]['id']}'; ");
						}
					}
				}
			}
		}
	} else {
  	$countMessage = serialize(isset( $bodyArray['header']['failures'][0]) ?  $bodyArray['header']['failures'][0] : []);
		$database->query( " UPDATE cfg_expand SET `countStat` = 999, `countRquota` = 0, `countMessage` = '{$countMessage}', `lastDatetime` = NOW() WHERE username = '{$user['username']}' ");
	}
}

run(function() use ($argv) {
	showMessage('获取搜索关键词数据.' );
	$config = getConfig();
	$database = new MySQL();
	$connect = $database->connect($config);
	if( $connect === false) {
		return;
	}
    $userList = $database->query('SELECT `id`, `companyId`, `userid`, `username`, `password`, `token`, `siteid` FROM cfg_expand where `status` = 1 and `userType` = 1 AND `siteid` > 0 ');
    if ($userList === false) {
    	showMessage($database->errno . ' - ' . $database->error);
    	return;
    }
    $userArray = array_chunk($userList, $config['curlnumber']);
    foreach ($userArray as $arrayList) {
    	foreach ($arrayList as $user) {
    		$siteArray = explode(',', $user['siteid']);
    		foreach ($siteArray as $siteid) {
    			if($siteid) {
    				go(function() use ($config, $user, $siteid)  {
    					$database = new MySQL;
    					$connect = $database->connect($config);
    					if( $connect === false) {
    						return;
    					}
    					showMessage($user['username'].'获取搜索关键词数据.' );
    					getSiteList(json_encode([
    						'header' => [ 'username'=> $user['username'], 'password'=> $user['password'], 'token'=> $user['token'], 'account_type'=> 1] ,
    						'body' => [
    							'site_id' => $siteid,
    							'metrics' => 'access_page,searchword,start_time',
    							'method' => 'trend/latest/a',
    							'source' => 'search,0',
    							'max_results' => 500
    						]
    					]), $database, $user);
    				});
    			}
    		}
    	}
    	Swoole\Coroutine::sleep(2);
    }

});

showMessage('执行耗时 ' . round((microtime(true) - $start_time), 3) . ' s');